var express = require('express');
var router = express.Router();

const db = require("../utils/dbconfig")

// 插入表数据
// 例如{
// 	···
// 	table:"introduce"//指向表
// }
router.post('/', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");

  console.log("req.body:", req.body)
  let data = req.body
  let table = data.table
  delete data.table;
  let params = data
  let sql = `insert into ${table} set ?`;
  // 'INSERT INTO users SET ?
  console.log("sql:" + sql)
  console.log("params:", params)
  db.sqlConnection(sql, params).then((res) => {
    console.log('res:', res)
  }).catch((err) => {
    console.log(err)
  })
  data = '插入成功'
  res.send(data)
});
// 删除信息
router.post('/delete', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");

  console.log("req.body:", req.body)
  let [data, table_name] = req.body
  let key = Object.keys(data)[0]
  console.log("key:", Object.keys(data)[0])

  let params = []
  let sql = `DELETE FROM ${table_name} WHERE ${key}=${data[key]};`;

  console.log("sql:" + sql)
  console.log("params:", params)
  db.sqlConnection(sql, params).then((result) => {
    // console.log('result:', result)
    res.send("删除成功")
  }).catch((err) => {
    console.log(err)
    res.send("删除失败")
  })

});
// 获取表信息
router.get('/', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");

  console.log(" req.query:", req.query)
  let params = []
  let sql = `select * from ${req.query.type}`;
  // 'INSERT INTO users SET ?
  console.log("sql:" + sql)
  console.log("params:", params)
  db.sqlConnection(sql, params).then((result) => {
    // console.log('result:', result)
    res.send(result)
  }).catch((err) => {
    console.log(err)
    res.send("未搜索到")
  })
});
// 获取商品类型信息
router.get('/goods', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");

  console.log(" req.query:", req.query)
  let params = []
  let sql = `select * from goods where goodsType='${req.query.type}'`;
  console.log("sql:" + sql)
  console.log("params:", params)
  db.sqlConnection(sql, params).then((result) => {
    // console.log('result:', result)
    res.send(result)
  }).catch((err) => {
    console.log(err)
    res.send("未搜索到")
  })
});
// 通过id获取商品类型信息
router.get('/goods_id', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");

  console.log(" req.query:", req.query)
  let params = []
  let sql = `select * from goods where goodsId='${req.query.goodsId}'`;
  console.log("sql:" + sql)
  console.log("params:", params)
  db.sqlConnection(sql, params).then((result) => {
    // console.log('result:', result)
    res.send(result)
  }).catch((err) => {
    console.log(err)
    res.send("未搜索到")
  })
});

module.exports = router;